/**
 * v-auth
 * 按钮权限指令
 */
import { useAuthStore } from '@/stores/modules/auth'
import type { Directive, DirectiveBinding } from 'vue'

const auth: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding
    if (!value) {
      return
    }
    if (value instanceof Array && value.length) {
      const hasPermission = value.every(item => validator(item))
      if (!hasPermission) el.remove()
    } else {
      if (!validator(value)) el.remove()
    }
  }
}

function validator(value: string) {
  const authStore = useAuthStore()
  const arr = value.split(':')
  let routeName, permission
  if (arr.length > 1) {
    routeName = arr[0]
    permission = arr[1]
  } else {
    routeName = authStore.routeName
    permission = value
  }
  const currentPageRoles = authStore.authButtonListGet[routeName] ?? []
  return currentPageRoles.includes(permission)
}

export default auth
